package com.yunsom.testdemo.multiple_thread.threadpooltest2;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * @author 10400
 * @create 2018-04-19 20:38
 */
public class FutureTest {

    //1、配置线程池
    private static ExecutorService es = Executors.newFixedThreadPool(20);

    //2、封装响应Feature
    class BizResult{
        public String orderId;
        public String  data;

        public String getOrderId() {
            return orderId;
        }

        public void setOrderId(String orderId) {
            this.orderId = orderId;
        }

        public String getData() {
            return data;
        }

        public void setData(String data) {
            this.data = data;
        }
    }


    //3、实现Callable接口
    class BizTask implements Callable {

        private String orderId;

        private Object data;

        //可以用其他方式
        private CountDownLatch countDownLatch;

        public BizTask(String orderId, Object data, CountDownLatch countDownLatch) {
            this.orderId = orderId;
            this.data = data;
            this.countDownLatch = countDownLatch;
        }

        @Override
        public Object call() {
            try {
                //todo business
                System.out.println("当前线程Id = " + this.orderId);
                BizResult br = new BizResult();
                br.setOrderId(this.orderId);
                br.setData("some key about your business" + this.getClass());
                return br;
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                //线程结束时，将计时器减一
                countDownLatch.countDown();
            }
            return null;
        }
    }

    /**
     * 业务逻辑入口
     */
    public List<Future> beginBusiness() throws InterruptedException {
        //模拟批量业务数据
        List<String> list = new ArrayList<>();
        for (int i = 0 ; i < 1000 ; i++) {
            list.add(String.valueOf(i));
        }
        //设置计数器
        CountDownLatch countDownLatch = new CountDownLatch(list.size());

        //接收多线程响应结果
        List<Future> resultList = new ArrayList<>();
        //begin thread
        for( int i = 0 ,size = list.size() ; i<size; i++){
            //todo something before thread
            resultList.add(es.submit(new BizTask(list.get(i), null, countDownLatch)));
        }
        //wait finish
        countDownLatch.await();
        return resultList;
    }

    public static void main(String[] args) throws InterruptedException {
        FutureTest ft = new FutureTest();
        List<Future> futures = ft.beginBusiness();
        System.out.println("futures.size() = " + futures.size());
        //todo some operate
        System.out.println(" ==========================end========================= " );
    }

}

